package studyguide.ch17;

import java.io.IOException;

import javax.microedition.io.ConnectionNotFoundException;
import javax.microedition.io.PushRegistry;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.DateField;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class AlarmSetMidlet extends MIDlet {

	private final Command setAlarmCommand;
	private final Command exitCommand;
	private final Display display;
	
	private final Form mainForm;
	private final DateField dateField;
	
	private class SampleCommandListener implements CommandListener {
		public void commandAction(Command command, Displayable displayable) {
			if (command == exitCommand) {
				destroyApp(true);
				notifyDestroyed();
			} else if (command == setAlarmCommand) {
				Thread thread = new Thread( new Runnable() {
					public void run() {
						Alert alert = new Alert("Success", "", null, AlertType.INFO);
						try {
							PushRegistry.registerAlarm("studyguide.ch17.ShowAlarmMidlet", dateField.getDate().getTime());
							alert.setString("Alarm created successfully");
						} catch (ConnectionNotFoundException e) {
							alert.setString("Error:" + e);
						} catch (ClassNotFoundException e) {
							alert.setString("Error:" + e);
						}
						display.setCurrent(alert);
					}
				});
				thread.start();
			} else {
				throw new RuntimeException("UNKNOWN COMMAND" + command);
			}
		}
	}
	
	public AlarmSetMidlet() throws IOException {
		mainForm = new Form("Set Alarm");
		exitCommand = new Command("Exit", Command.EXIT, 1);
		setAlarmCommand = new Command("Set alarm", Command.SCREEN, 1);
		
		mainForm.addCommand(setAlarmCommand);
		mainForm.addCommand(exitCommand);
		
		SampleCommandListener listener = new SampleCommandListener();
		mainForm.setCommandListener(listener);
		display = Display.getDisplay(this);
		dateField = new DateField("Time", DateField.DATE_TIME);
		mainForm.append(dateField);
	}
	
	protected void destroyApp(boolean unconditional) {
	}

	protected void pauseApp() {
	}

	protected void startApp() throws MIDletStateChangeException {
		display.setCurrent(mainForm);	
	}

}
